package com.allqj.sfx.infrastructure;

import com.allqj.sfx.domain.service.AuthenticationService;
import com.allqj.sfx.infrastructure.enums.ResultStatusCodeEnum;
import com.allqj.sfx.infrastructure.exceptions.BusinessException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * @author sjw
 * @className UserPermissionInterceptor
 * @date 2022/7/19 16:34
 * @description: 用户权限验证
 */
@Component
public class UserPermissionInterceptor implements HandlerInterceptor {

    private final AuthenticationService authenticationService;
    private final String OPTIONS="OPTIONS";
    public UserPermissionInterceptor(AuthenticationService authenticationService) {
        this.authenticationService = authenticationService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        if(OPTIONS.equals(request.getMethod())){
            response.setStatus(HttpServletResponse.SC_OK);
            return false;
        }
        String token = request.getHeader("token");
        Optional.ofNullable(token).orElseThrow(() -> new BusinessException(ResultStatusCodeEnum.NOT_LOGIN.getCode(), ResultStatusCodeEnum.NOT_LOGIN.getMessage()));
        authenticationService.validate(token);
        return true;
    }
}
